<template>
  <el-dialog
    :title="mode === 'add' ? '新增设备评估' : '编辑设备评估'"
    v-model="visibleLocal"
    width="80%"
    append-to-body
    @close="resetForm"
  >
    <el-form
      ref="assessmentRef"
      :model="form"
      :rules="rules"
      label-width="220px"
      label-position="right"
      class="assessment-form"
    >
      <el-row :gutter="20">

        <!-- 基础信息 -->
        <el-col :span="12">
  <el-form-item label="设备名称" prop="assetId">
    <el-cascader
      v-model="rootPath"
      :props="cProps"
      clearable
      filterable
      placeholder="请选择设备路径"
      style="width: 100%"
      show-all-levels
      :disabled="!!form.assetId"    
    >
      <template #default="{ node, data }">
        <div class="cas-opt">
          <span class="cas-label" :title="data.label">{{ data.label }}</span>
          <el-tag
            v-if="typeLabelOf(node, data)"
            size="small"
            :type="typeTagType(typeLabelOf(node, data))"
            effect="light"
            class="cas-badge"
          >
            {{ typeLabelOf(node, data) }}
          </el-tag>
        </div>
      </template>
      <template #tag="{ node, data }">
        <span class="sel-tag">
          {{ data.label }}
          <span class="sel-type" v-if="typeLabelOf(node, data)">
            （{{ typeLabelOf(node, data) }}）
          </span>
        </span>
      </template>
    </el-cascader>
  </el-form-item>
</el-col>


        <el-col :span="12">
          <el-form-item label="备件选择" prop="spareId">
  <el-select
    v-model="form.spareId"
    multiple
    filterable
    clearable
    :disabled="spareSelectDisabled"    
    placeholder="请选择备件（可多选）"
    style="width: 100%"
    @visible-change="(val) => val && reloadOptions()"
  >
    <el-option
      v-for="op in allOptions"
      :key="op.value"
      :label="op.label"
      :value="op.value"
    />
  </el-select>
</el-form-item>


        </el-col>


        <el-col :span="12">
          <el-form-item label="初始日期" prop="initialDate">
            <el-date-picker
              v-model="form.initialDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择初始日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="分数" prop="score">
            <el-input v-model="form.score" placeholder="请输入分数" />
          </el-form-item>
        </el-col>

        <!-- 新增部分：维护工种、备件数量、计划内容 -->
        <el-col :span="12">
          <el-form-item label="维护工种" prop="maintainType">
            <el-select
              v-model="form.maintainType"
              multiple
              clearable
              filterable
              placeholder="请选择维护工种（可多选）"
              collapse-tags                
              collapse-tags-tooltip        
              style="width: 100%"
            >
              <el-option
                v-for="dict in asset_trade_code"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>

            <!-- <el-select
  v-model="form.maintainType"
  multiple
  collapse-tags
  collapse-tags-tooltip
  placeholder="请选择维护工种（可多选）"
  style="width: 100%"
>
  
  <template #header>
    <div
      style="padding: 6px 12px; cursor: pointer; color: #409EFF;"
      @click.stop="toggleSelectAll"
    >
      {{ isAllSelected ? '取消全选' : '全选' }}
    </div>
    <el-divider style="margin: 4px 0" />
  </template>

  <el-option
    v-for="dict in asset_trade_code"
    :key="dict.value"
    :label="dict.label"
    :value="parseInt(dict.value)"
  />
</el-select> -->


          </el-form-item>
        </el-col>

        


        <el-col :span="12">
          <el-form-item label="备件数量" prop="spareCount">
            <el-input v-model="form.spareCount" placeholder="请输入备件数量" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="计划内容" prop="planContent">
            <editor v-model="form.planContent" :min-height="192" />
          </el-form-item>
        </el-col>

        <!-- 风险评分 -->
        <el-col :span="12" v-for="item in scoreFields" :key="item.prop">
          <el-form-item :label="item.label" :prop="item.prop">
            <el-input v-model="form[item.prop]" :placeholder="`请输入${item.label}`" />
          </el-form-item>
        </el-col>

        <!-- 状态选择 -->
        <el-col :span="12">
          <el-form-item label="是否处理" prop="isDeal">
            <el-select v-model="form.isDeal" placeholder="请选择">
              <el-option label="未处理" :value="0" />
              <el-option label="已处理" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="删除状态" prop="isDelete">
            <el-select v-model="form.isDelete" placeholder="请选择状态">
              <el-option
                v-for="dict in asset_delete"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 备注 -->
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">
          {{ mode === 'add' ? '新增' : '更新' }}
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed, nextTick} from 'vue'
import { ElMessage } from 'element-plus'
import { listAssessment, getAssessment, delAssessment, addAssessment, updateAssessment } from "@/api/sbtz/assessment"
import { listSpare } from "@/api/sbtz/spare" // 备件接口 
import { cascaderChildren,getLeafNodePath } from "@/api/sbtz/sbtz"; 

const allOptions = ref([])
const rootPath = ref([]);
const spareSelectDisabled = ref(false);

// ---- props & emits ----
const props = defineProps({
  visible: Boolean,
  mode: { type: String, default: 'add' },
  rowData: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['update:visible', 'success'])

const visibleLocal = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
})

// 将各种形态的 id 规范成 [Number, ...]
function normalizeIdArray(src) {
  if (!src) return [];
  if (Array.isArray(src)) return src.map(v => Number(v)).filter(Boolean);
  if (typeof src === 'string') {
    return src.split(',').map(v => Number(v.trim())).filter(Boolean);
  }
  return [Number(src)].filter(Boolean);
}

// ---- 表单数据 ----
const form = reactive({
  id: null,
  assetId: '',
  spareId: '',
  initialDate: '',
  score: '',
  grade: '',
  standby: '',
  quality: '',
  safetyHealth: '',
  environment: '',
  impact: '',
  criticalLevel: '',
  mtbf: '',
  mttr: '',
  cost: '',
  severity: '',
  severityLevel: '',
  totalFactorScore: '',
  equipmentriskLevel: '',
  isDeal: 0,
  isDelete: 0,
  remark: '',
  // 新增字段
  maintainType: [],
  spareCount: '',
  planContent: '',
  spareId: [],
})

// ---- 下拉选项 ---- 
const { proxy } = getCurrentInstance();
const { asset_trade_code, asset_delete } = proxy.useDict('asset_trade_code', 'asset_delete');

const scoreFields = [
  { label: '等级', prop: 'grade' },
  { label: 'STANDBY 备用评分', prop: 'standby' },
  { label: 'QUALITY 质量评分', prop: 'quality' },
  { label: 'SAFETY/HEALTH 安全健康', prop: 'safetyHealth' },
  { label: 'ENVIRONMENT 环境', prop: 'environment' },
  { label: 'IMPACT 影响', prop: 'impact' },
  { label: 'CRITICAL LEVEL 关键等级', prop: 'criticalLevel' },
  { label: 'MTBF 平均故障间隔', prop: 'mtbf' },
  { label: 'MTTR 平均修复时间', prop: 'mttr' },
  { label: 'COST 成本', prop: 'cost' },
  { label: 'SEVERITY 严重性', prop: 'severity' },
  { label: 'SEVERITY LEVEL 等级', prop: 'severityLevel' },
  { label: 'TOTAL FACTOR SCORE 总评分', prop: 'totalFactorScore' },
  { label: 'EQUIPMENT RISK LEVEL 风险等级', prop: 'equipmentriskLevel' },
]

const rules = {
  assetId: [{ required: true, message: '请选择设备', trigger: 'blur' }],
  spareId: [{ required: true, message: '请选择备件', trigger: 'blur' }],
  maintainType: [{ required: true, message: '请选择维护工种', trigger: 'change' }],
}

// 级联属性配置（保持懒加载逻辑）
// const cProps = {
//   checkStrictly: true,
//   emitPath: true,
//   value: "id",
//   label: "label",
//   lazy: true,
//   lazyLoad: (node, resolve) => {
//     const parentId = node.level === 0 ? 0 : node.value;
//     cascaderChildren(parentId)
//       .then((res) => resolve(res?.data || []))
//       .catch(() => resolve([]));
//   },
// };


const cProps = {
  checkStrictly: true,
  emitPath: true,
  value: "id",
  label: "label",
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const parentId = node.level === 0 ? 0 : node.value;

    try {
      const res = await cascaderChildren(parentId);
      let list = res?.data || [];

      // ✅ 情况：mode = anyDevice，仅加载到子设备层级
      list = list.map((x) => {
          const type = x.nodeType || x.node_type;
          // SYSTEM、MACHINE、MODULE 是允许的，但 MODULE 为最后一级（leaf）
          if (type === "MACHINE") {
            return { ...x, leaf: true }; // 子设备层停止加载
          }
          return x;
      });

      resolve(list);
    } catch {
      resolve([]);
    }
  },
};


// 节点类型标签映射
function typeLabelOf(node, data) {
  const TYPE_LABELS = {
    SYSTEM: "系统",
    MACHINE: "母设备",
    MODULE: "子设备",
    COMPONENT: "部件",
    PART: "零件",
  };
  const code = data && (data.nodeType || data.node_type);
  if (code && TYPE_LABELS[code]) return TYPE_LABELS[code];

  // 按层级兜底
  const lv = node && typeof node.level === "number" ? node.level : 0;
  if (lv <= 1) return "系统";
  if (lv === 2) return "母设备";
  if (lv === 3) return "子设备";
  if (lv === 4) return "部件";
  return "零件";
}

function typeTagType(label) {
  const map = {
    系统: "success",
    母设备: "primary",
    子设备: "warning",
    部件: "warning",
    零件: "info",
  };
  return map[label] || "info";
}

// 异步加载备件库
// 异步加载备件列表
async function reloadOptions() {
  try {
    const res = await listSpare({ pageNum: 1, pageSize: 9999 })
    const list = res?.rows ?? res?.data ?? []
    allOptions.value = list.map((r) => ({
      value: r.id,
      label: r.name || `备件 ${r.id}`,
    }))
  } catch (e) {
    console.error("加载备件失败", e)
  }
}



// ✅ 选中设备后更新 assetId
function handleCascaderChange(val) {
  if (Array.isArray(val) && val.length) {
    form.assetId = val[val.length - 1]; // 取选中路径最后一级 ID
  } else {
    form.assetId = null;
  }
}

// ✅ 编辑模式：如果有 assetId，则加载路径并禁用选择
// --- 初始化判断逻辑：判断上级是否传递 assetId --- 
watch(
  () => props.rowData,
  async (val) => {
    if (!val) return;

    // 提取有效的设备 ID（优先 id，其次 assetId） 
    const targetId = val.assetId || val.id;
     
    if (targetId) {
      try {
        const res = await getLeafNodePath(targetId);
        rootPath.value = (res?.data || []).map((x) => x.id);
        form.assetId = targetId;
      } catch (err) {
        console.error('加载设备路径失败:', err);
        rootPath.value = [];
        form.assetId = targetId;
      }
    } else {
      // ✅ 没有 id / assetId → 可自由选择
      rootPath.value = [];
      form.assetId = null;
    }
  },
  { immediate: true }
);


const isAllSelected = computed(() =>
  form.maintainType.length === asset_trade_code.value.length
);

function toggleSelectAll() {
  if (isAllSelected.value) {
    form.maintainType = [];
  } else {
    form.maintainType = asset_trade_code.value.map(i => parseInt(i.value));
  }
}



watch(rootPath, (val) => {
  if (Array.isArray(val) && val.length) {
    form.assetId = val[val.length - 1]; // 最后一级节点ID
  }
});
// ---- 默认选中逻辑 ----
// 如果 rowData（编辑模式）传入了 spareId，则自动设置选中
watch(
  () => props.rowData,
  (val) => {
    if (props.mode === "edit" && val) {
      // 统一为数组格式
      if (Array.isArray(val.spareId)) {
        form.spareId = val.spareId
      } else if (typeof val.spareId === "string" && val.spareId.includes(",")) {
        form.spareId = val.spareId.split(",").map((v) => Number(v))
      } else if (val.spareId) {
        form.spareId = [Number(val.spareId)]
      }
    }
  },
  { immediate: true }
)

// ---- 监听：编辑时加载 rowData ----
watch(
  () => props.rowData,
  (val) => {
    if (props.mode === 'edit' && val) Object.assign(form, val)
  },
  { immediate: true }
)

// ✅ 监听上级 rowData：优先 spareInfos，否则用 spareId；且 spareId 场景禁用下拉
watch(
  () => props.rowData,
  async (val) => {
    if (!val) return;

    // 先准备好下拉选项，避免选中值不在 options 时的视觉落差
    await reloadOptions();

    // 1) 优先：spareInfos -> 提取 id/spareId
    if (Array.isArray(val.spareInfos) && val.spareInfos.length) {
      const ids = val.spareInfos
        .map(s => Number(s.id ?? s.spareId))
        .filter(Boolean);
      form.spareId = Array.from(new Set(ids)); // 去重
      spareSelectDisabled.value = false;       // ✅ spareInfos 场景不禁用
      return;
    }

    // 2) 回退：spareId 字段（可能是数组/逗号串/单值）
    if (val.spareId != 0 && val.spareId !== '') {
      form.spareId = Array.from(new Set(normalizeIdArray(val.spareId)));
      spareSelectDisabled.value = true;        // ✅ 回填场景禁用选择
      return;
    }

    // 3) 都没有：清空并可选
    form.spareId = [];
    spareSelectDisabled.value = false;
  },
  { immediate: true }
);

// ---- 重置表单 ----
function resetForm() {
  for (const key in form) form[key] = Array.isArray(form[key]) ? [] : ''
  form.isDeal = 0
  form.isDelete = 0
}

// ---- 关闭 ----
function closeDialog() {
  visibleLocal.value = false
  resetForm()
}

// ---- 提交逻辑 ----
const assessmentRef = ref(null)
async function submitForm() {
  assessmentRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (props.mode === 'add') {
        await addAssessment(form)
        ElMessage.success('新增成功')
      } else {
        await updateAssessment(form)
        ElMessage.success('更新成功')
      }
      emit('success')
      visibleLocal.value = false
      resetForm()
    } catch {
      ElMessage.error('操作失败')
    }
  })
}
</script>

<style scoped>
.assessment-form {
  padding: 10px 20px;
}
.el-form-item {
  margin-bottom: 10px;
}
.el-form-item__label {
  font-weight: 500;
  color: #444;
  line-height: 36px;
  white-space: nowrap;
}
.dialog-footer {
  text-align: right;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
}

.cas-opt {
  display: flex;
  align-items: center;
  gap: 6px;
}
.cas-label {
  max-width: 360px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.cas-badge {
  margin-left: auto;
}

:deep(.el-form-item) {
  margin-bottom: 16px;  
  position: relative;   
}
 

</style>
